package com.lizhongbao.cloud.db.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lizhongbao.cloud.db.domain.dto.TestTableDto;
import com.lizhongbao.cloud.db.domain.dto.TestTableSaveDto;
import com.lizhongbao.cloud.db.domain.eo.TestTable;
import com.lizhongbao.cloud.db.service.ITestTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.lizhongbao.cloud.db.common.BaseController;

import javax.validation.Valid;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lizhongbao
 * @since 2019-12-17
 */
@RestController
@RequestMapping("/test-table")
public class TestTableController extends BaseController {

    @Autowired
    private ITestTableService iTestTableService;

    @GetMapping("/count")
    public Integer count() {
        return iTestTableService.count();
    }

    @GetMapping("/getMaxAge")
    public Integer getMaxAge() {
        return iTestTableService.getMaxAge();
    }

    @GetMapping()
    public JSONObject page(@RequestParam(name = "page", required = false, defaultValue = "1") Long page,
                           @RequestParam(name = "size", required = false, defaultValue = "10") Long size,
                           @RequestBody TestTableDto dto) {
        return JSONObject.parseObject(JSONObject.toJSONString(iTestTableService.pageVo(page, size, dto), SerializerFeature.WriteMapNullValue));
    }

    @GetMapping("/{id:[a-zA-Z0-9]+}")
    public JSONObject get(@PathVariable Long id) {
        return JSONObject.parseObject(JSONObject.toJSONString(iTestTableService.getById(id), SerializerFeature.WriteMapNullValue));
    }

    @PostMapping("")
    public JSONObject create(@RequestBody @Valid TestTableSaveDto dto) {
        TestTable testTable = new TestTable();
        BeanUtil.copyProperties(dto, testTable);
        iTestTableService.save(testTable);
        return JSONObject.parseObject(JSONObject.toJSONString(testTable, SerializerFeature.WriteMapNullValue));
    }

    @PutMapping("/{id:[a-zA-Z0-9]+}")
    public JSONObject update(@PathVariable Long id, @RequestBody @Valid TestTableSaveDto dto) {
        TestTable old = iTestTableService.getById(id);
        BeanUtil.copyProperties(dto, old, CopyOptions.create().setIgnoreNullValue(true));
        iTestTableService.updateById(old);
        return JSONObject.parseObject(JSONObject.toJSONString(old, SerializerFeature.WriteMapNullValue));
    }

    @DeleteMapping("/{id:[a-zA-Z0-9]+}")
    public String remove(@PathVariable Long id) {
        return iTestTableService.removeById(id) + "";
    }

}
